import { Friends } from '/imports/models/Friends';

Template.home_friends.onCreated(function() {
  this.query = new ReactiveVar({});
  this.searchText = new ReactiveVar();
  
  this.infiniteScroll({
    query: {
      user_id: Meteor.userId()
    },
    publication: 'get.friends',
    countPublication: 'get.friends.counts'
  });

});

Template.home_friends.helpers({
  results: function() {
    return Friends.find(Template.instance().query.get(), {
      limit: Template.instance().getLimit()
    });
  },
  loading: function() {
    return !Template.instance().resultSub.ready();
  }
});

Template.home_friends.events({
  'input #search-friend'(event, instance) {
    instance.searchText.set(event.target.value);
    let searchText = $.trim(instance.searchText.get());
    if (!searchText || searchText.length === 0) {
      instance.query.set({});
    } else {
      instance.query.set({
        'info.username': { $regex: new RegExp(searchText) }
      });
    }
  }
});
